package com.xysq.activity;

import android.content.Intent;
import android.content.res.AssetFileDescriptor;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.ImageButton;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.rockcent.kcupon.zxing.AbstractQRCodeScanActivity;
import com.rockcent.kcupon.zxing.camera.CameraManager;
import com.rockcent.kcupon.zxing.decoding.CaptureActivityHandler;
import com.rockcent.kcupon.zxing.decoding.InactivityTimer;
import com.rockcent.kcupon.zxing.utils.Constants;
import com.rockcent.kcupon.zxing.view.ViewfinderView;
import com.umeng.analytics.MobclickAgent;
import com.xysq.lemon.R;
import com.xysq.util.CollectionUtil;
import com.xysq.util.QRCodeUtil;
import com.xysq.util.ToastUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Vector;

public class QRCodeScanActivity extends AbstractQRCodeScanActivity
        implements SurfaceHolder.Callback, View.OnClickListener {

    private static final String TAG = "QRCodeScanActivity";

    private static final long MESSAGE_RESTART_DELAY = 1500L;

    private CaptureActivityHandler handler;
    private ViewfinderView viewfinderView;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private ImageButton backIbtn;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_qrcode_scan);
        MobclickAgent.openActivityDurationTrack(false);
        CameraManager.init(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        initView();
    }

    private void initView() {
        backIbtn = (ImageButton)findViewById(R.id.ibtn_back);
        backIbtn.setOnClickListener(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("扫一扫页");
        MobclickAgent.onResume(this);
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("扫一扫页");
        MobclickAgent.onPause(this);
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();

        String resultString = result.getText();
        if (TextUtils.isEmpty(resultString)) {
            ToastUtil.showShort(this, R.string.toast_qrcode_not_correct);
            // Restart preview
            handler.sendEmptyMessageDelayed(
                    Constants.MESSAGE_RESTART_PREVIEW, MESSAGE_RESTART_DELAY);
            return;
        }

        HashMap<String, Long> params = QRCodeUtil.parseUrl(resultString);
        if (CollectionUtil.isNullOrEmpty(params.values())) {
            ToastUtil.showShort(this, R.string.toast_qrcode_not_correct);
            finish();
            return;
        }
        if (params.get(QRCodeUtil.PARAM_ID) <= 0) {
            ToastUtil.showShort(this, R.string.toast_qrcode_not_correct);

            handler.sendEmptyMessageDelayed(
                    Constants.MESSAGE_RESTART_PREVIEW, MESSAGE_RESTART_DELAY);
            return;
        }
        long couponId = params.get(QRCodeUtil.PARAM_ID);
        Intent intent = new Intent(this, CommodityDetailsActivity.class);
        intent.putExtra(CommodityDetailsActivity.COUPONMODEL_ID, (int) couponId);
        long channelId = 0;
        if (resultString.lastIndexOf("channelId") != -1) {
            channelId = params.get(QRCodeUtil.PARAM_CHANNEL_ID);
        }
        long customerId = 0;
        if (resultString.lastIndexOf("customerId") != -1) {
            customerId = params.get(QRCodeUtil.PARAM_CUSTOMER_ID);
        }
        intent.putExtra(CommodityDetailsActivity.CHANNEL_ID, (int) channelId);
        intent.putExtra(CommodityDetailsActivity.CUSTOMER_ID, (int) customerId);
        startActivity(intent);
//        }

        finish();
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            ioe.printStackTrace();
            Log.d(TAG, "initCamera" + "add add add camera error");
        } catch (RuntimeException e) {
            Log.d(TAG, "initCamera" + "runtime");
            e.printStackTrace();
        }
        if (handler == null) {
            handler = new CaptureActivityHandler(this, decodeFormats, characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        Log.d(TAG, "surfaceChanged" + "format:" + format + "width:" + width + "height:" + height);
    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        Log.d(TAG, "surfaceChanged" + "holder:" + holder);
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }
    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        Log.d(TAG, "surfaceDestroyed" + "holder:" + holder);
        hasSurface = false;
    }

    @Override
    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    @Override
    public Handler getHandler() {
        return handler;
    }

    @Override
    public void drawViewfinder() {
        viewfinderView.drawViewfinder();
    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

    @Override
    public void onClick(View view) {
        if (view == backIbtn) {
            finish();
        }
    }
}